package com.plugin;

import com.edu.DispatcherServlet;
import com.edu.factory.HandlerFactory;
import demo.bean.BeanFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CreateClassLoader implements ServletContextListener {

    private static final String SCAN_PACKAGE="scanPackage";

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            //通过web.xml来判断有没有使用插件
            String path = servletContextEvent.getServletContext().getInitParameter(SCAN_PACKAGE);
            BeanFactory factory = new BeanFactory(path);
            HandlerFactory containerFactory = new ContainerHandlerFactory(factory);
            servletContextEvent.getServletContext().setAttribute(DispatcherServlet.ACTION_FACTORY,containerFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ContainerHandlerFactory containerFactory = (ContainerHandlerFactory) servletContextEvent.getServletContext().getAttribute(DispatcherServlet.ACTION_FACTORY);
        containerFactory.getBeanFactory().close();
        servletContextEvent.getServletContext().removeAttribute(DispatcherServlet.ACTION_FACTORY);
    }
}
